package com.kwlt.smc.service;

import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.kwlt.smc.dao.UserChannelDao;
import com.kwlt.smc.entity.Blacklist;
import com.kwlt.smc.entity.Channel;
import com.kwlt.smc.entity.PipelineResponse;
import com.kwlt.smc.entity.SmsInfo;
import com.kwlt.smc.entity.User;
import com.kwlt.smc.util.CacheMap;
import com.kwlt.smc.util.Constants;
import com.kwlt.smc.util.JedisKey;
import com.kwlt.smc.web.SendSmsController;


/**
 * 黑名单管理类
 * 
 * @author wangweiheng
 * 
 */
// Spring Bean的标识.
@Component
public class BlacklistService {
	//全局黑名单
	List<Blacklist> globalBlacklist=null;
	//通道黑名单
	Map<String,List<Blacklist>> channelMap=null;
	//用户黑名单
	Map<String,List<Blacklist>> userMap=null;
	//运营商黑名单
	Map<String,List<Blacklist>> operatorsMap=null;
	private static Logger logger = LoggerFactory.getLogger(SendSmsController.class);
	@Autowired
	private UserChannelDao userChannelDao;
	
	public boolean validationBlack(SmsInfo smsInfo) {
		if( StringUtils.isEmpty(smsInfo.getDest())){
			return false;
		}
		// 如果不需要过滤
		String isFilterBlack=smsInfo.getOuser().getIsFilterBlack();
		if (StringUtils.isEmpty(isFilterBlack) || "1".equals(isFilterBlack)) {
			return true;
		} else if ("0".equals(isFilterBlack)) {
			//如果需要过滤
			//List<Keyword> list=getKeywordList();
			return filterBlackListFromRedis(smsInfo);
		} else {
			return true;
		}
	}
	
	/**
	 * 通过redis过滤黑名单信息
	 * @param smsInfo
	 * @return
	 */
	private boolean filterBlackListFromRedis(SmsInfo smsInfo){
		List<Channel> channelList = userChannelDao.getChannelByLoginName(smsInfo.getUser());
		User user = smsInfo.getOuser();
		//判断全局黑名单
		JedisService jedis = new JedisService(Constants.REDIS_IP,Constants.REDIS_PASSWORD);
		filterBlackGlobal(jedis, smsInfo);
		//判断运营商的黑名单
		filterBlackListOpertors(smsInfo, jedis);
		//判断通道的黑名单
		filterBlackListChannel(smsInfo, jedis, channelList);
		//判断用户的黑名单
		filterBlackListUser(smsInfo, jedis, user);
		//判断用户类型的黑名单
		filterBlackListForUserCategory(smsInfo, jedis, user);
		//断开redis
		jedis.closeJedis();
		//如果没过滤完，继续发送，否则停止发送
		if(StringUtils.isBlank(smsInfo.getDest())){
			return false;
		}else{
			return true;
		}
	}
	
	/**
	 * 校验全局
	 * @param jedis
	 * @param smsInfo
	 */
	private void filterBlackGlobal(JedisService jedis,SmsInfo smsInfo){
		List<PipelineResponse<Boolean>> globalList = jedis.hexists(JedisKey.GLOBAL_BLACK_PREFIX, smsInfo.getDest());
		if(globalList!=null && globalList.size()>0){
			for(PipelineResponse<Boolean> resp:globalList){
				if(resp.getResponse().get()){
					//则存在黑名单
					removePhone(smsInfo,resp.getPhone(),"global");
				}
			}
		}
	}
	
	/**
	 * 过滤用户黑名单
	 * @param smsInfo
	 * @param jedis
	 * @param user
	 */
	private void filterBlackListUser(SmsInfo smsInfo,JedisService jedis,User user){
		List<PipelineResponse<Boolean>> userList = 
			jedis.hexists(JedisKey.USER_BLACK_PREFIX+user.getUserNumbers(), smsInfo.getDest());
		if(userList!=null && userList.size()>0){
			for(PipelineResponse<Boolean> resp:userList){
				if(resp.getResponse().get()){
					//则存在黑名单
					removePhone(smsInfo,resp.getPhone(),"user:"+user.getUserNumbers());
				}
			}
		}
	}
	/**
	 * 过滤用户类别黑名单
	 * @param smsInfo
	 * @param jedis
	 * @param user
	 */
	private void filterBlackListForUserCategory(SmsInfo smsInfo,JedisService jedis,User user){
		String category = user.getUserCategory();
		if(!StringUtils.isBlank(category)){
			List<PipelineResponse<Boolean>> userCategoryList = 
				jedis.hexists(JedisKey.USER_CATEGORY_BLACK_PREFIX+category, smsInfo.getDest());
			if(userCategoryList!=null && userCategoryList.size()>0){
				for(PipelineResponse<Boolean> resp:userCategoryList){
					if(resp.getResponse().get()){
						//则存在黑名单
						removePhone(smsInfo,resp.getPhone(),"user category:"+user.getUserCategory());
					}
				}
			}
		}
	}
	
	/**
	 * 过滤通道黑名单
	 * @param smsInfo
	 * @param jedis
	 * @param channelList
	 */
	private void filterBlackListChannel(SmsInfo smsInfo,JedisService jedis,List<Channel> channelList){
		if(channelList!=null && channelList.size()>0){
			for(Channel channel:channelList){
				List<PipelineResponse<Boolean>> channelBlackList = 
					jedis.hexists(JedisKey.CHANNEL_BLACK_PREFIX+channel.getNumbers(), smsInfo.getDest());
				
				if(channelBlackList!=null && channelBlackList.size()>0){
					for(PipelineResponse<Boolean> resp:channelBlackList){
						if(resp.getResponse().get()){
							//则存在黑名单
							System.out.println(resp.getResponse().get());
							removePhone(smsInfo,resp.getPhone(),"channel:"+channel.getNumbers());
						}
					}
				}
			}
		}
	}
	
	/**
	 * 判断运营商的黑名单
	 * @param smsInfo
	 * @param jedis
	 */
	private void filterBlackListOpertors(SmsInfo smsInfo,JedisService jedis){
		List<PipelineResponse<Boolean>> mobileList = jedis.hexists(JedisKey.OPERATORS_BLACK_PREFIX+Constants.MOBILE, smsInfo.getDest());
		if(mobileList!=null && mobileList.size()>0){
			for(PipelineResponse<Boolean> resp:mobileList){
				if(resp.getResponse().get()){
					//则存在黑名单
					removePhone(smsInfo,resp.getPhone(),"mobile");
				}
			}
		}
		List<PipelineResponse<Boolean>> telecomList = jedis.hexists(JedisKey.OPERATORS_BLACK_PREFIX+Constants.TELECOM, smsInfo.getDest());
		if(telecomList!=null && telecomList.size()>0){
			for(PipelineResponse<Boolean> resp:telecomList){
				if(resp.getResponse().get()){
					//则存在黑名单
					removePhone(smsInfo,resp.getPhone(),"telecom");
				}
			}
		}
		List<PipelineResponse<Boolean>> unicomList = jedis.hexists(JedisKey.OPERATORS_BLACK_PREFIX+Constants.UNICOM, smsInfo.getDest());
		if(unicomList!=null && unicomList.size()>0){
			for(PipelineResponse<Boolean> resp:unicomList){
				if(resp.getResponse().get()){
					//则存在黑名单
					removePhone(smsInfo,resp.getPhone(),"unicom");
				}
			}
		}
	}
	
	/**
	 * 通过本机缓存过滤黑名单
	 * @param smsInfo
	 * @return
	 */
	private boolean filterBlacklist(SmsInfo smsInfo) {
		//判断全局黑名单
		List<Channel> channelList = userChannelDao.getChannelByLoginName(smsInfo.getUser());
		User user = smsInfo.getOuser();
		globalBlacklist=CacheMap.globalBlacklist;
		channelMap=CacheMap.channelMap;
		userMap=CacheMap.userMap;
		operatorsMap=CacheMap.operatorsMap;
		//boolean boo=false;
		if(globalBlacklist!=null && globalBlacklist.size()>0){
			for(Blacklist balcklist:globalBlacklist){
				if(smsInfo.getDest().indexOf(balcklist.getPhoneNumber())>-1){
					//System.out.println(balcklist.getPhoneNumber()+"是全局黑名单");
					removePhone(smsInfo,balcklist.getPhoneNumber(),"global");
					//boo=true;
				}
			}
		}
		
		//判断运营商黑名单
		if(operatorsMap!=null && operatorsMap.size()>0){
			//移动
			List<Blacklist> mobileList=operatorsMap.get(Constants.MOBILE);
			if(mobileList!=null && mobileList.size()>0){
				for(Blacklist balcklist:mobileList){
					if(smsInfo.getDest().indexOf(balcklist.getPhoneNumber())>-1){
						//System.out.println(balcklist.getPhoneNumber()+"是移动运营商黑名单");
						removePhone(smsInfo,balcklist.getPhoneNumber(),"mobile");
						//boo=true;
					}
				}
			}
			//联通
			List<Blacklist> unicomList=operatorsMap.get(Constants.UNICOM);
			if(unicomList!=null && unicomList.size()>0){
				for(Blacklist balcklist:unicomList){
					if(smsInfo.getDest().indexOf(balcklist.getPhoneNumber())>-1){
						//System.out.println(balcklist.getPhoneNumber()+"是联通运营商黑名单");
						removePhone(smsInfo,balcklist.getPhoneNumber(),"unicom");
						//boo=true;
					}
				}
			}
			//电信
			List<Blacklist> telecomList=operatorsMap.get(Constants.TELECOM);
			if(telecomList!=null && telecomList.size()>0){
				for(Blacklist balcklist:telecomList){
					if(smsInfo.getDest().indexOf(balcklist.getPhoneNumber())>-1){
						//System.out.println(balcklist.getPhoneNumber()+"是电信运营商黑名单");
						removePhone(smsInfo,balcklist.getPhoneNumber(),"telecom");
						//boo=true;
					}
				}
			}
		}
		
		//判断通道黑名单
		if(channelMap!=null && channelMap.size()>0){
			for(Channel channel:channelList){
				List<Blacklist> channelBlackList=channelMap.get(channel.getNumbers());
				if(channelBlackList!=null && channelBlackList.size()>0){
					for(Blacklist balcklist:channelBlackList){
						if(smsInfo.getDest().indexOf(balcklist.getPhoneNumber())>-1){
							//System.out.println(balcklist.getPhoneNumber()+"是通道"+channel.getNumbers()+"的黑名单");
							removePhone(smsInfo,balcklist.getPhoneNumber(),"channel:"+channel.getNumbers());
							//boo=true;
						}
					}
				}
			}
		}
		

		//判断用户黑名单
		if(userMap!=null && userMap.size()>0){
			List<Blacklist> userBlackList= userMap.get(user.getUserNumbers());
			if(userBlackList!=null && userBlackList.size()>0){
				for(Blacklist balcklist:userBlackList){
					if(smsInfo.getDest().indexOf(balcklist.getPhoneNumber())>-1){
						//System.out.println(balcklist.getPhoneNumber()+"是用户"+user.getUserName()+"的黑名单");
						removePhone(smsInfo,balcklist.getPhoneNumber(),"user:"+user.getUserNumbers());
						//boo=true;
					}
				}
			}
		}
		//return boo;
		//如果没过滤完，继续发送，否则停止发送
		if(StringUtils.isBlank(smsInfo.getDest())){
			return false;
		}else{
			return true;
		}
	}


	private void removePhone(SmsInfo smsInfo, String phoneNumber,String log) {
		String phone=smsInfo.getDest();
		if(phone.equals(phoneNumber)){
			logger.info(log + " mobblack:"+smsInfo.getUser()+"\t"+phoneNumber+"\t"+smsInfo.getMsg());
			smsInfo.setDest("");
		}else if(phone.startsWith(phoneNumber)){//判断第一个号码是否是黑名单
			//logger.info(smsInfo.getUser()+"\t"+phoneNumber+"\t2"+smsInfo.getMsg());
			smsInfo.setDest(phone.replaceAll(phoneNumber+",", ""));
			removePhone(smsInfo,phoneNumber,log);
		}else{
			logger.info(log + " mobblack:"+smsInfo.getUser()+"\t"+phoneNumber+"\t"+smsInfo.getMsg());
			smsInfo.setDest( phone.replaceAll(","+phoneNumber, ""));
		}
	}
	public static void main(String[] args) {
		String phone="13810514135,13810514136,13810514137,13810514138";
		String phoneNumber="13810514138";
		if(phone.startsWith(phoneNumber)){//判断第一个号码是否是黑名单
			System.out.println(phone.replaceAll(phoneNumber+",", ""));
		}else{
			System.out.println(phone.replaceAll(","+phoneNumber, ""));
		}
		
	}
}
